import { memo, useCallback } from 'react'
import { useEffect } from 'react'
import { useState } from 'react'
import { useMemo } from 'react'

const Parent = ({ items, mapFunc, prefix }) => {
  console.log(prefix, 'Parent render', items)
  return (
    <>
      <h2>{prefix}</h2>
      {items.map(mapFunc.bind(null, prefix))}
    </>
  )
}

const Child = ({ item, prefix }) => {
  console.log(prefix, 'Child render', item)
  return <div>Child: {item}</div>
}

const StaticComponent = () => {
  console.log('Static render')
  return <h2>Static</h2>
}

const StateComponent = () => {
  const [counter, setCounter] = useState(0)

  useEffect(() => {
    async function a() {
      setCounter(10)
      await new Promise((resolve) => setTimeout(resolve, 0))

      setCounter(11)
      setCounter(12)
    }
    a()
  }, [])

  const onClick = async () => {
    setCounter(1)
    setCounter(2)

    await new Promise((resolve) => setTimeout(resolve, 0))

    setCounter(3)
    setCounter(4)
    setCounter(5)
  }

  console.log('***', counter)

  return <button onClick={onClick}>render { counter }</button>
}

const MemoStaticComponent = memo(StaticComponent)
const MemoParentComponent = memo(Parent)

let g = null

const FCProfilingDemo = () => {
  const [foo, setFoo] = useState(false)
  const [count, setCount] = useState(3)
  const arr = [1, 2, 3, 4, 5]
  const arr2 = useMemo(() => [1, 2, 3, 4, 5], [])
  const arr3 = useMemo(
    () => [...Array(count)].map((_, index) => index + 1),
    [count]
  )

  const mapFunc1 = useCallback(
    (prefix, item, index) => <Child key={index} prefix={prefix} item={item} />,
    []
  )

  console.log(g === mapFunc1)
  g = mapFunc1

  return (
    <>
      <button onClick={() => setFoo(!foo)}>
        toggle foo={foo ? 'true' : 'false'}
      </button>
      <button onClick={() => setCount(count + 1)}>count={count}</button>
      <Parent items={arr} prefix="简单属性" mapFunc={mapFunc1} />

      <Parent items={arr2} prefix="memo简单属性" mapFunc={mapFunc1} />

      <MemoParentComponent
        items={arr}
        prefix="memoParent1简单属性"
        mapFunc={mapFunc1}
      />

      <MemoParentComponent
        items={arr2}
        prefix="memoParent2简单属性"
        mapFunc={mapFunc1}
      />

      <MemoParentComponent
        items={arr3}
        prefix="memoParent3简单属性"
        mapFunc={mapFunc1}
      />
      <StaticComponent />
      <MemoStaticComponent />

      <StateComponent />
    </>
  )
}

export default FCProfilingDemo
